<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2016-6-21
 * Func   管理员组
 */
defined('IN_YuLin') || exit('NO PERMIT!');

$table = Table('admin_group');
$mtable = Table('admin_menu');

if(IS_POST)
{
    //  权限
    if($a == 'permit')
    {
        $permit = is_array($_POST['menuid']) ? implode(',',$_POST['menuid']) : '';
        
        $id = intval($_REQUEST['id']);
        $db->exec('UPDATE '.$table.' SET permit = \''.$permit.'\' WHERE id = '.$id);
        
        ShowMsg('修改权限成功！',U($m.'/'.$c.'/'.$a,['id'=>$id]));
    }
    
    //  角色添加 or 修改
    $id = intval($_REQUEST['id']);
    $data = $id ? $db->getrow('SELECT * FROM '.$table.' WHERE id = '.$id) : [];
    
    //  表单数据
    $post = $_POST['data'];
    
    $ins = [];
    $ins['name']=   NoBadStr($post['name']);
    
    if($data['id']) //  修改
    {
        $db->exec('UPDATE '.$table.' SET '.CreateUpdateSql($ins).' WHERE id = '.$data['id']);
    }
    else
    {
        $ins['dateline'] = TIMESTAMP;
        
        $db->exec('INSERT INTO '.$table.CreateInsertSql($ins));
    }
    
    ShowMsg('操作成功','?m='.$m.'&c='.$c);
}

if($a == 'add')
{
    $id = intval($_GET['id']);  //  修改分类
    $data = $id ? $db->getrow('SELECT * FROM '.$table.' WHERE id = '.$id) : [];
    
    $tpl->display('admin/group_add');
}
else if($a == 'permit')
{
    $id = intval($_GET['id']);  //  修改分类
    $data = $id ? $db->getrow('SELECT * FROM '.$table.' WHERE id = '.$id) : [];
    !$data && exit('角色不存在！');
    
    $data['permit'] = explode(',',$data['permit']); //  各个菜单id逗号隔开
    
    include_once(LIB_PATH.'class/Tree.class.php');

    $tree = new Tree();
    $result = $db->getall('SELECT * FROM '.$mtable.' WHERE 1 ORDER BY sort DESC');
    
	$tree->icon = array('│ ','├─ ','└─ ');
	$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	$modules = 'admin,system';
	foreach ($result as $n=>$t)
    {
		$result[$n]['checked'] = in_array($t['id'],$data['permit']) ? ' checked' : '';//    权限判断
		$result[$n]['level'] = MenuLevel($t['id'],$result);
		$result[$n]['parentid_node'] = $t['pid'] ? ' class="child-of-node-'.$t['pid'].'"' : '';
	}
	$str  = "<tr id='node-\$id' \$parentid_node data-pid='\$pid'><td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuid[]' value='\$id' data-level='\$level' data-pid='\$pid' \$checked onclick='javascript:checknode(this);'> \$name</td></tr>";

	$tree->init($result);
	$menu = $tree->get_tree(0, $str);
    
    $tpl->display('admin/group_permit');
}
else
{
    $data = $db->getall('SELECT * FROM '.$table.' ORDER BY id');
    
    $tpl->display('admin/group');
}

?>